package com.jdkreader.annotation.db;


import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @DBTable系列注解的处理器例子
 */
public class TableCreator {

    public static void main(String[] args) {
        handleAnnotation(Member.class);
    }

    public static void handleAnnotation(Class<?> cl){

        DBTable dbTable = cl.getAnnotation(DBTable.class);
        if(null == dbTable){
            System.out.println("No DBTable Annotation");
        }
        String tableName = dbTable.name();
        //tableName is null,use the className
        if(tableName.length() < 1) {
            tableName = cl.getName().toUpperCase();
        }
        List<String> columnDefs = new ArrayList<String>();
        //get all fields,includes public,private..etc
        for(Field field : cl.getDeclaredFields()){
            String columnName = null;
            Annotation[] anns=field.getDeclaredAnnotations();
            if(anns.length < 1){
                continue; // not a column
            }

            //默认第一个注解为数据类型
            if(anns[0] instanceof SQLInteger){
                SQLInteger sqlInteger = (SQLInteger) anns[0];
                if(sqlInteger.name().length() < 1) {
                    columnName = field.getName().toUpperCase();
                } else {
                    columnName = sqlInteger.name();
                }

                columnDefs.add(columnName + " INT " +
                        getConstraints(sqlInteger.constraints()));
            }

            if(anns[0] instanceof SQLString){
                SQLString sqlString = (SQLString) anns[0];
                if(sqlString.name().length() < 1) {
                    columnName = field.getName().toUpperCase();
                } else {
                    columnName = sqlString.name();
                }

                columnDefs.add(columnName + " VARCHAR " +
                        getConstraints(sqlString.constraints()) + " VALUE "+
                        sqlString.value());
            }
        }

        StringBuilder createCommand = new StringBuilder(
                " CREATE TABLE " + tableName + "(");

        for(String columnDef : columnDefs){
            createCommand.append("\n    "+columnDef+",");
        }

        //去掉建表语句末尾的'，'并添加'）'
        String tableCreation = createCommand.substring(
                0,createCommand.length() -1) + (");");

        System.out.println("Table Creation SQL for "+
                tableName +" is: \n "+tableCreation);
    }

    //get column's information about Constraints
    private static String getConstraints(Constraints con){

        String constraints = "";
        if(!con.allowNUll()){
            constraints += "NOT NULL";
        }
        if(con.primaryKey()){
            constraints += " PRIMARY KEY ";
        }
        if(con.unique()){
            constraints += " UNIQUE ";
        }
        return constraints;
    }
}
